/*background.js*/
var task
var background = {
	init: function () {
		//首次运行 set ttsOption
		chrome.storage.local.get('ttsoption', function (items) {
			if (items.ttsoption) {
				console.log('ttsoption setted')
			} else {
				background.ttsOptionRest()
			}
		});
		//监控消息
		chrome.runtime.onMessage.addListener(
			function (request, sender, sendResponse) {
				switch (request.action) {
					case "TTSMessage":
						background.ttsMessage(request.content)
						console.log(request)
						// sendResponse({
						// 	success: 'tts onMessage success'
						// })
						break;
					default:
						break;
				}
				sendResponse();
		});

		//同步chrome storage 和local storage
		chrome.storage.onChanged.addListener(function () {
			chrome.storage.local.get(['sendmsg', 'wellcomemsg'], function (items) {
				console.log('chrome storage发生改变')
				console.log(items)
				sendmsg = items.sendmsg
				wellcomemsg = items.wellcomemsg
				// doubanfm = items.doubanfm
				chrome.windows.getAll(function (wins) {
					wins && wins.forEach(function (win) {
						chrome.tabs.query({
							windowId: win.id
						}, function (tabs) {
							tabs && tabs.forEach(function (tab) {
								var url = tab.url;
								if (url.indexOf('douyu') > -1
									|| url.indexOf('zhanqi.tv') > -1) {
									var tabId = tab.id;
									chrome.tabs.sendMessage(tabId, {
										action: 'sendmsg',
										content: sendmsg
									}, function (response) { });
									chrome.tabs.sendMessage(tabId, {
										action: 'wellcomemsg',
										content: wellcomemsg
									}, function (response) { });
								}
							});
						});
					});
				})
			});
		});
		/*监控关闭窗口*/
		chrome.windows.onRemoved.addListener(function (windowId) {
			console.log(windowId)
			chrome.storage.local.get('doubanfmWindow', function (item) {
				if (item.doubanfmWindow.id == windowId) {
					chrome.storage.local.set({
						'doubanfm': 0
					})
				};
			})

		})
	},
	ttsMessage: function (msg) {
		chrome.storage.local.get('ttsoption', function (items) {
			ttsoption = items.ttsoption;
			chrome.tts.speak(msg, ttsoption);
		})
		if (chrome.extension.lastError) {
			console.log('TTS Error: ' + chrome.extension.lastError.message);
		}
	},
	ttsOptionRest: function () {
		if (globalThis.navigator.userAgent.indexOf("Macintosh") > 0) {
			ttsoption = {
				"lang": "zh-CN",
				"voiceName": "Ting-Ting",
				"gender": "female",
				"rate": 1,
				"pitch": 1,
				"volume": 1,
				'enqueue': true
			}
		} else if (globalThis.navigator.userAgent.indexOf("Windows") > 0) {
			ttsoption = {
				"lang": "zh-CN",
				"voiceName": "native",
				"rate": 1,
				"pitch": 1,
				"volume": 1,
				'enqueue': true
			}
		} else {
			ttsoption = {
				"lang": "zh-CN",
				"rate": 1,
				"pitch": 1,
				"volume": 1,
				'enqueue': true
			}
		}
		chrome.storage.local.set({
			'ttsoption': ttsoption
		})
	}
}

background.init()
